package com.lj.api.tools.Qniu;

import com.google.gson.Gson;
import com.lj.api.common.CommUtils;
import com.lj.api.common.WebUtil;
import com.lj.api.conifg.URL;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.processing.OperationManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by Leon on 2015/11/17 0017.
 */
public class QNiuTools {

    private static final Properties properties;
    static {
        properties = new Properties();
        InputStream in = QNiuTools.class.getClassLoader().getResourceAsStream("QiNiu.properties");
        try {
            properties.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static final String AK = (String) properties.get("AK");
    public static final String SK = (String) properties.get("SK");
    private static final String SCOPE = (String) properties.get("SCOPE");
    private static final String SCOPE1 = (String) properties.get("SCOPE1");
    private static final String SCOPE_DOMAIN = (String) properties.get("SCOPE_DOMAIN");
    private static final String SCOPE_DOMAIN1 = (String) properties.get("SCOPE_DOMAIN1");
    private static String queryProgressAPI = (String) properties.get("queryProgressAPI");
    private static String IP = (String) properties.get("IP");


    private static Auth auth = Auth.create(AK, SK);

    /**
     * 获取私有空间绑定的域名
     * @return
     */
    public static String getScopeDomain1(){
        return SCOPE_DOMAIN1;
    }

    /**
     * 获取公有空间绑定的域名
     * @return
     */
    public static String getScopeDomain(){
        return SCOPE_DOMAIN;
    }

    /**
     * 获取公有空间
     * @return
     */
    public static String getScope(){
        return SCOPE;
    }

    /**
     * 获取私有空间
     * @return
     */
    public static String getScope1(){
        return SCOPE1;
    }

    public static String getAppVideoToken(String fileKey,String type){
        String bucktname = SCOPE;
        if (type.equals("0")){
            bucktname = SCOPE;
        }else if(type.equals("1")){
            bucktname = SCOPE1;
        }
        StringMap stringMap = new StringMap();
        stringMap.put("callbackUrl","http://" + IP + "/json/qNiuAppMap4CallBack.htm");
        stringMap.put("callbackBody","key=$(key)&hash=$(etag)&size=$(fsize)&uid=$(x:uid)&path=$(x:path)&persistentId=$(persistentId)");
        String sKey = getKeyByName("section") + ".mp4";
        String opts = "avthumb/mp4/ab/160k/ar/44100/acodec/libfaac/r/30/vb/800k/vcodec/libx264/s/1280x720/autoscale/1/stripmeta/0|saveas/" + CommUtils.encodeBase64(bucktname + ":" + sKey);
        stringMap.put("persistentOps",opts);
        stringMap.put("persistentPipeline","dkmq1");
        return auth.uploadToken(bucktname,fileKey, 3600, stringMap, true);
    }

    public static String getAppVideoToken(String fileKey,String type,String videoSecond){
        String bucktname = SCOPE;
        if (type.equals("0")){
            bucktname = SCOPE;
        }else if(type.equals("1")){
            bucktname = SCOPE1;
        }
        StringMap stringMap = new StringMap();
        stringMap.put("callbackUrl","http://" + IP + "/json/qNiuAppMp4ImageCallBack.htm");
        stringMap.put("callbackBody","key=$(key)&hash=$(etag)&size=$(fsize)&uid=$(x:uid)&path=$(x:path)&loadType=$(x:loadType)&persistentId=$(persistentId)");
        String sKey = getKeyByName("section") + ".mp4";


        String opts ="avthumb/mp4/ab/160k/ar/44100/acodec/libfaac/r/30/vb/800k/vcodec/libx264/s/1280x720/autoscale/1/stripmeta/0|saveas/" + CommUtils.encodeBase64(bucktname + ":" + sKey );
        stringMap.put("persistentOps",opts);
        stringMap.put("persistentPipeline","dkmq1");
        return auth.uploadToken(bucktname,fileKey, 3600, stringMap, true);

    }

    /**
     * 获取视频文件的上传凭证
     * @param key 文件的key
     * @param returnUrl 通知的地址
     * @param videoSecond 截取视频缩略图的秒数
     * @param width 截取图片的宽度
     * @param height 截取图片的高度
     * @return
     */
    public static String getUpToken(String key, String returnUrl, String imgKey, Integer videoSecond, Integer width, Integer height,String type){

        String bucktname = SCOPE;
        if (type.equals("公有空间")){
            bucktname = SCOPE;
        }else if(type.equals("私有空间")){
            bucktname = SCOPE1;
        }

        StringMap stringMap = new StringMap();
        stringMap.put("returnUrl",returnUrl);
        stringMap.put("returnBody","{'key':$(key),'duration':$(avinfo.video.duration),'fname':$(fname),'bucket':$(bucket),'fsize':$(fsize),'mimeType':$(mimeType),'persistentId':$(persistentId),'imgKey':$(x:imgKey)}");
        String sKey = getKeyByName("section") + ".mp4";
        String opts = "";
       /* if(videoSecond == null || WebUtil.checkEmpty(imgKey)){
            opts = "avthumb/m3u8/segtime/5/vb/440k|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + sKey );
        }else{
            opts = "vframe/jpg/offset/" + videoSecond + "/w/" + width + "/h/" + height +
                    "|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + (imgKey + ".jpg") ) +
                    ";avthumb/m3u8/segtime/5/vb/440k|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + sKey );
        }*/
        if(videoSecond == null || WebUtil.checkEmpty(imgKey)){
            opts = "avthumb/mp4/ab/160k/ar/44100/acodec/libfaac/r/30/vb/800k/vcodec/libx264/s/1280x720/autoscale/1/stripmeta/0|saveas/" + CommUtils.encodeBase64(bucktname + ":" + sKey );
        }else{
            opts = "vframe/jpg/offset/" + videoSecond + "/w/" + width + "/h/" + height +
                    "|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + (imgKey + ".jpg") ) +
                    ";avthumb/mp4/ab/160k/ar/44100/acodec/libfaac/r/30/vb/800k/vcodec/libx264/s/1280x720/autoscale/1/stripmeta/0|saveas/" + CommUtils.encodeBase64(bucktname + ":" + sKey );
        }
        stringMap.put("persistentOps",opts);
        stringMap.put("persistentPipeline","dkmq1");
        return auth.uploadToken(bucktname,key, 3600, stringMap, true);
    }

    /**
     * 生成课件上传凭证
     * @param key
     * @param returnUrl
     * @return
     */
    public static String getCourceToken(String key, String returnUrl){
        String bucktname = SCOPE;
        StringMap stringMap = new StringMap();
        stringMap.put("returnUrl",returnUrl);
        stringMap.put("returnBody","{'key':$(key),'bucket':$(bucket),'fsize':$(fsize),'cname':$(x:cname),'price':$(x:price),'sub':$(x:sub),'timetableid':$(x:timetableid)}");
        /*String opts = "saveas/" + CommUtils.encodeBase64(bucktname + ":" + key );
        stringMap.put("persistentOps",opts);
        stringMap.put("persistentPipeline","dkmq1");*/

        return auth.uploadToken(bucktname,key,3600, stringMap ,true);
    }

    /**
     * 生成APP版本上传Token
     * @param key 上传后保存的key
     * @param returnUrl 上传后的回调地址
     * @return
     */
    public static String getVersionToken(String key, String returnUrl){
        StringMap stringMap = new StringMap();
        stringMap.put("returnUrl",returnUrl);
        stringMap.put("returnBody","{'key':$(key),'fname':$(fname),'bucket':$(bucket),'fsize':$(fsize),'mimeType':$(mimeType), 'version':$(x:version),'versionCode':$(x:versionCode), 'type':$(x:type), 'updateType':$(x:updateType), 'updateDesc':$(x:updateDesc)}");
        return auth.uploadToken(SCOPE,key, 3600, stringMap, true);
    }


    /**
     * 生成音频文件上传的Token
     * @param key
     * @param returnUrl
     * @return
     */
    public static String getAudioUpToken(String key, String returnUrl){
        StringMap stringMap = new StringMap();
        stringMap.put("returnUrl",returnUrl);
        stringMap.put("returnBody","{'key':$(key),'fname':$(fname),'bucket':$(bucket),'fsize':$(fsize),'mimeType':$(mimeType)}");
        String sKey = getKeyByName("audio") + ".mp3";
        String opts = "avthumb/mp3|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + sKey );
        stringMap.put("persistentOps",opts);
        return auth.uploadToken(SCOPE, sKey , 3600, stringMap, true);
    }


    /**
     * 生成音频文件上传的Token
     * @return
     */
    public static String getAppImagesUpToken(String skey,String buffix,String method){
        if(method.equals("userImg")) {
            StringMap stringMap = new StringMap();
            stringMap.put("callbackUrl", "http://" + IP + "/json/qNiuAppImageCallBack.htm");
            stringMap.put("callbackHost", URL.url);
            stringMap.put("callbackBody", "key=$(key)&hash=$(etag)&w=$(imageInfo.width)&h=$(imageInfo.height)&size=$(fsize)&uid=$(x:uid)&path=$(x:path)");
            String opts = "avthumb/" + buffix + "|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + skey);
            stringMap.put("persistentOps", opts);
            stringMap.put("fsizeLimit", 5*1024 * 1024);
            stringMap.put("mimeLimit", "image/*");
            stringMap.put("callbackFetchKey", 1);
            return auth.uploadToken(SCOPE, skey , 3600, stringMap, true);
        }else if (method.equals("commentImg")){
            StringMap stringMap = new StringMap();
            stringMap.put("callbackUrl", "http://" + IP + "/json/qNiuAppCommentImageCallBack.htm");
            stringMap.put("callbackHost", URL.url);
            stringMap.put("callbackBody", "key=$(key)&hash=$(etag)&w=$(imageInfo.width)&h=$(imageInfo.height)&size=$(fsize)&uid=$(x:uid)&path=$(x:path)");
            String opts = "avthumb/" + buffix + "|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + skey);
            stringMap.put("persistentOps", opts);
            stringMap.put("fsizeLimit", 5*1024 * 1024);
            stringMap.put("mimeLimit", "image/*");
            stringMap.put("callbackFetchKey", 1);
            return auth.uploadToken(SCOPE, skey , 3600, stringMap, true);
        }else if (method.equals("mp3")){
            StringMap stringMap = new StringMap();
            stringMap.put("callbackUrl", "http://" + IP + "/json/qNiuAppMap3CallBack.htm");
            stringMap.put("callbackHost", URL.url);

            stringMap.put("callbackBody", "key=$(key)&hash=$(etag)&size=$(fsize)&uid=$(x:uid)&path=$(x:path)&time=$(x:recordtime)");
            String opts = "avthumb/" + buffix + "|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + skey);
            stringMap.put("persistentOps", opts);
            stringMap.put("fsizeLimit", 10*1024 * 1024);
            //stringMap.put("mimeLimit", "audio/x-mpeg;audio/mpeg;application/*");
            stringMap.put("callbackFetchKey", 1);

            System.out.println(stringMap);

            return auth.uploadToken(SCOPE, skey , 3600, stringMap, true);
        }/*else if (method.equals("mp4")){
            StringMap stringMap = new StringMap();
            stringMap.put("callbackUrl", "http://" + IP + "/json/qNiuAppMap4CallBack.htm");
            stringMap.put("callbackHost", URL.url);
            stringMap.put("callbackBody", "key=$(key)&hash=$(etag)&size=$(fsize)&uid=$(x:uid)&path=$(x:path)&recordtime=$(x:recordtime)");
            String opts = "avthumb/" + buffix + "|saveas/" + CommUtils.encodeBase64(SCOPE1 + ":" + skey);
            stringMap.put("persistentOps", opts);
            stringMap.put("fsizeLimit", 10*1024 * 1024);
            stringMap.put("mimeLimit", "audio/x-mpeg;audio/mpeg;application/*");
            stringMap.put("callbackFetchKey", 1);

            System.out.println(stringMap);

            return auth.uploadToken(SCOPE1, skey , 3600, stringMap, true);
        }*/else if (method.equals("jpg") || method.equals("jpeg")){
            StringMap stringMap = new StringMap();
            stringMap.put("callbackUrl", "http://" + IP + "/json/qNiuAppCommentImageCallBack.htm");
            stringMap.put("callbackHost", URL.url);
            stringMap.put("callbackBody", "key=$(key)&hash=$(etag)&w=$(imageInfo.width)&h=$(imageInfo.height)&size=$(fsize)&uid=$(x:uid)&path=$(x:path)");
            String opts = "avthumb/" + buffix + "|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + skey);
            stringMap.put("persistentOps", opts);
            stringMap.put("fsizeLimit", 5*1024 * 1024);
            stringMap.put("mimeLimit", "image/*");
            stringMap.put("callbackFetchKey", 1);
            return auth.uploadToken(SCOPE, skey , 3600, stringMap, true);
        }
        else if (method.equals("pdf")){
            StringMap stringMap = new StringMap();
            stringMap.put("callbackUrl", "http://" + IP + "/json/qNiuAppCommentImageCallBack.htm");
            stringMap.put("callbackHost", URL.url);
            stringMap.put("callbackBody", "key=$(key)&hash=$(etag)&w=$(imageInfo.width)&h=$(imageInfo.height)&size=$(fsize)&uid=$(x:uid)&path=$(x:path)&fileName=$(x:fileName)");
            String opts = "avthumb/" + buffix + "|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + skey);
            stringMap.put("persistentOps", opts);
            stringMap.put("fsizeLimit", 50*1024 * 1024);
            stringMap.put("mimeLimit", "audio/x-mpeg;audio/mpeg;application/*");
            stringMap.put("callbackFetchKey", 1);
            return auth.uploadToken(SCOPE, skey , 3600, stringMap, true);
        }else{
            StringMap stringMap = new StringMap();
            stringMap.put("callbackUrl", "http://" + IP + "/json/qNiuAppCommentImageCallBack.htm");
            stringMap.put("callbackHost", URL.url);
            stringMap.put("callbackBody", "key=$(key)&hash=$(etag)&w=$(imageInfo.width)&h=$(imageInfo.height)&size=$(fsize)&uid=$(x:uid)&path=$(x:path)");
            String opts = "avthumb/" + buffix + "|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + skey);
            stringMap.put("persistentOps", opts);
            stringMap.put("fsizeLimit", 5*1024 * 1024);
            stringMap.put("mimeLimit", "image/*");
            stringMap.put("callbackFetchKey", 1);
            return auth.uploadToken(SCOPE, skey , 3600, stringMap, true);
        }
    }

    public static String getImagesUpToken(String skey,String buffix,String method){
        StringMap stringMap = new StringMap();
        stringMap.put("returnUrl",URL.url);
        stringMap.put("returnBody","{'key':$(key),'fname':$(fname),'bucket':$(bucket),'fsize':$(fsize),'mimeType':$(mimeType), 'version':$(x:version), 'type':$(x:type), 'updateType':$(x:updateType), 'updateDesc':$(x:updateDesc)}");
        String opts = "avthumb/" + buffix + "|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + skey);
        stringMap.put("persistentOps", opts);
        stringMap.put("fsizeLimit", 3*1024 * 1024);
        stringMap.put("mimeLimit", "image/*");
        return auth.uploadToken(SCOPE, skey , 3600, stringMap, true);
    }

    public static String getImaUpToken(String fileName){
        StringMap stringMap = new StringMap();
        //stringMap.put("returnUrl",URL.url);
        stringMap.put("returnBody","{'name':$(fname),'size':$(fsize),'w':$(imageInfo.width),'h':$(imageInfo.height)}");
        //String opts = "avthumb/" + buffix + "|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + fileName);
        //stringMap.put("persistentOps", opts);
        stringMap.put("fsizeLimit", 3*1024 * 1024);
        stringMap.put("mimeLimit", "image/*");
        return auth.uploadToken(SCOPE, fileName , 3600, stringMap, true);
    }

    /**
     * 生成MP3上传Token
     * @param fileName
     * @return
     */
    public static String getMp3Token(String fileName){
        StringMap stringMap = new StringMap();
        stringMap.put("returnBody","{'name':$(fname),'size':$(fsize),'time':$(avinfo.audio.duration)}");
        String opts = "avthumb/mp3|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + fileName);
        stringMap.put("persistentOps", opts);
        stringMap.put("fsizeLimit", 10*1024 * 1024);
        stringMap.put("mimeLimit", "audio/*;application/*");
        return auth.uploadToken(SCOPE, fileName , 3600, stringMap, true);
    }

    /**
     * 获取MP4上传Token
     * @param fileName
     * @return
     */
    public static String getMp4Token(String fileName){
        StringMap stringMap = new StringMap();
        stringMap.put("returnBody","{'name':$(fname),'size':$(fsize),'time':$(avinfo.audio.duration)}");
        String opts = "avthumb/mp4|saveas/" + CommUtils.encodeBase64(SCOPE + ":" + fileName);
        stringMap.put("persistentOps", opts);
        stringMap.put("fsizeLimit", 100*1024 * 1024);
        stringMap.put("mimeLimit", "video/*;application/*");
        return auth.uploadToken(SCOPE, fileName , 3600, stringMap, true);
    }

    public static String pfopsMp3(String key){
        OperationManager operater = new OperationManager(auth);
        String fops = "avthumb/mp3";
        String pfops = fops + "|saveas/"+CommUtils.encodeBase64(SCOPE + ":" + key);
        //设置转码的队列
        String pipeline = "dkmq1";
        StringMap params = new StringMap().putWhen("force", 1, true).putNotEmpty("pipeline", pipeline);
        try {
            String persistid = operater.pfop(SCOPE, key, pfops, params);
            //打印返回的persistid
            System.out.println(persistid);
        } catch (QiniuException e) {
            e.printStackTrace();
            //捕获异常信息
            Response r = e.response;
            // 请求失败时简单状态信息
            System.out.println(r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
                e.printStackTrace();
            } catch (QiniuException e1) {
                //ignore
                e.printStackTrace();
            }
        }
        return "";
    }


    public static String pfops(String key,String buffix){
        OperationManager operater = new OperationManager(auth);
        String fops = "avthumb/"+buffix;
        String pfops = fops + "|saveas/"+ CommUtils.encodeBase64(SCOPE + ":" + key);
        //设置转码的队列
        String pipeline = "dkmq1";
        StringMap params = new StringMap().putWhen("force", 1, true).putNotEmpty("pipeline", pipeline);
        try {
            String persistid = operater.pfop(SCOPE, key, pfops, params);
            //打印返回的persistid
            System.out.println(persistid);
        } catch (QiniuException e) {
            e.printStackTrace();
            //捕获异常信息
            Response r = e.response;
            // 请求失败时简单状态信息
            System.out.println(r.toString());
            try {
                // 响应的文本信息
                System.out.println(r.bodyString());
                e.printStackTrace();
            } catch (QiniuException e1) {
                //ignore
                e.printStackTrace();
            }
        }
        return "";
    }


    /**
     * 查询预处理进度情况
     * @param persistentId 预处理动作Id
     * @return 预处理进度信息集合
     */
    public static Map queryProgress(String persistentId){
        String result = WebUtil.sendURL(queryProgressAPI + persistentId);
        Gson gson = new Gson();
        Map map = gson.fromJson(result, HashMap.class);
        return map;
    }


    /**
     * 上传文件的键值生成策略
     * 年/月/日/时分秒毫秒+随机数
     * @param dirName key的文件夹标识名称
     * @return
     */
    public static String getKeyByName(String dirName){
        Calendar nowTime = new GregorianCalendar();
        int year = nowTime.get(Calendar.YEAR);
        int month = nowTime.get(Calendar.MONTH);
        int date = nowTime.get(Calendar.DATE);
        int hour = nowTime.get(Calendar.HOUR);
        int miniter = nowTime.get(Calendar.MINUTE);
        int second = nowTime.get(Calendar.SECOND);
        int mSecond = nowTime.get(Calendar.MILLISECOND);
        Random random = new Random();
        return new StringBuffer().append(dirName + "/")
                .append(year).append("/")
                .append(month + 1).append("/")
                .append(date).append("/")
                .append(hour).append(miniter).append(second).append(mSecond)
                .append(random.nextInt(10)).append(random.nextInt(10)).append(random.nextInt(10)).toString();

    }

    public static String voucherUrl(String url,long time){
        return auth.privateDownloadUrl(url,time);
    }

    public static void main(String[] args){
       /*Calendar nowTime = new GregorianCalendar();
        long time=nowTime.getTime().getTime()+60;*/
        //System.out.println(QNiuTools.voucherUrl("http://r2.yingyanghome.com/mp4/2018/9/14/44556710312.mp4"));
        /*Date date=new Date();
        date.setTime(1451491200);
        System.out.println(CommUtil.formatTime("yyyy-mm-dd",date));*/
        //System.setProperty("user.timezone","GMT +08");
        /*long time=System.currentTimeMillis();*/
        /*long time=(1537242672l)*1000;
        Date date=new Date();
        date.setTime(time);
        System.out.println(CommUtil.formatTime("yyyy-MM-dd hh:mm:ss",date));*/

        /*String msg = QNiuImageSetting.prefop("z0.5be4e65238b9f349c85da144");
        System.out.println(msg);*/
    }


}
